package boardgamer.common.client;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.LinearLayout;
import boardgamer.yavalath.client.threads.GameThread;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public abstract class AbstractActivity<V extends AbstractView<?>> extends Activity {
  
  private final int layoutId;
  private final int containerId;
  protected V view;
  protected GameThread gameThread;

  protected AbstractActivity(int layoutId, int containerId) {
    this.layoutId = layoutId;
    this.containerId = containerId;
  }

  public final void update(int elapsedTime) {
    this.handleUpdate(elapsedTime);
  }

  /**
   * Called when the activity and view are fully loaded
   */
  public final void ready() {
    this.handleReady();
    gameThread.startGame();
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(layoutId);

    view = checkNotNull(createView(), "view");
    ((LinearLayout) findViewById(containerId)).addView(view);
    gameThread = new GameThread(view, this);
    handleCreate(savedInstanceState);
  }

  @Override
  protected final void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    handleSaveInstanceState(outState);
  }

  @Override
  protected final void onStart() {
    super.onStart();
    handleStart();
  }

  @Override
  protected final void onStop() {
    super.onStop();
    Logger.log(Log.ERROR, view + " - stopping");
    gameThread.terminateGameThread();
    handleStop();
  }

  @Override
  protected final void onResume() {
    super.onResume();
    Logger.log(Log.ERROR, view + " - resuming");
    handleResume();
  }

  @Override
  protected final void onRestart() {
    super.onRestart();
    Logger.log(Log.ERROR, view + " - restarting");
    handleRestart();
  }

  @Override
  protected final void onPause() {
    super.onPause();
    Logger.log(Log.ERROR, view + " - pausing");
    gameThread.pause();
    handlePause();
  }

  @Override
  protected final void onDestroy() {
    super.onDestroy();
    Logger.log(Log.ERROR, view + " - destroying");
    handleDestroy();
  }

  protected abstract V createView();

  protected abstract void handleCreate(Bundle savedInstanceState);

  protected abstract void handleSaveInstanceState(Bundle outState);

  protected abstract void handleStart();

  protected abstract void handleReady();

  protected abstract void handleStop();

  protected abstract void handleResume();

  protected abstract void handleRestart();

  protected abstract void handlePause();

  protected abstract void handleDestroy();

  protected abstract void handleUpdate(int elapsedTime);
}
